--
-- Author: shunguo.chen
-- Date: 2016-06-21 13:10:17
--
-- TabsCheckBox

local modeName = string.getModeName(...)
local ClassRef = class(modeName)

ClassRef._tabs = nil
ClassRef._callBack = nil
ClassRef._default = nil
ClassRef._binds = nil

ClassRef._pressedBtn = nil

--是否点击一选中的按钮依然响应事件
ClassRef._isAlwaysHander = nil
--选择改变执行的方法
ClassRef._selectFunc = nil

function ClassRef:ctor(tabs, callBack, default, binds, selectFunc)
	self._tabs = tabs or {}
	self._callBack = callBack
	self._default = default or 1	
	self._binds = binds
	
	self._isAlwaysHander = false
	self._selectFunc = selectFunc

	for index, tabBtn in pairs(self._tabs) do	
		tabBtn:setSelected(false)
	    self:addEvent(index, tabBtn)
	end

    self:pressBtn(self._default, true)
end

function ClassRef:addEvent(index, tabBtn)
	local function onCheckBox(sender, eventType)
		self:pressBtn(index, true)
	end
	tabBtn:addEventListener(onCheckBox)
end

function ClassRef:addCheckBox(checkBox, index)
	self._tabs[index] = checkBox
	self:addEvent(index, checkBox)
end

function ClassRef:setAlwaysHander(b)
	self._isAlwaysHander = b
end

function ClassRef:setBtnSelected(btn, b)
	btn:setSelected(b)
	executeFunc(self._selectFunc, btn, b)
end

function ClassRef:pressBtn(index, isCallBack)
	local tabBtn = self._tabs[index]
	if self._pressedBtn ~= tabBtn then
	    local preBtn = self._pressedBtn	    
	    self._pressedBtn = tabBtn
	    if preBtn then
	    	self:setBtnSelected(preBtn, false)
	    end 
	    self:setBtnSelected(self._pressedBtn, true)
	    	    
	    if nil ~= self._binds then
	        for key, panel in pairs(self._binds) do
	            panel:setVisible(key == index)
	        end
	    end
	    
	    if nil ~= self._callBack and isCallBack then
	        self._callBack(index, self._pressedBtn)
	    end
	else
		self:setBtnSelected(self._pressedBtn, true)
		if self._isAlwaysHander then
			if nil ~= self._callBack and isCallBack then
			    self._callBack(index, self._pressedBtn)
			end
		end
	end
end

function ClassRef:setTouchEnabled(enable)
	for index, tabBtn in pairs(self._tabs) do
		tabBtn:setTouchEnabled(enable)
	end
end

function ClassRef:initSelectStatus()
	if nil ~= self._pressedBtn then
		self:setBtnSelected(self._pressedBtn, false)
	    self._pressedBtn = nil
	end
end

function ClassRef:setSelected(index)
	self:pressBtn(index, false)
end

function ClassRef:getBtn(index)
	return self._tabs[index]
end

return ClassRef